package com.xcw.jac.deoc;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xcw
 * @date 2023/8/9 14:17
 * @description 使用自定义注解实现的动态设置表格清单的值实现自动
 */
public class MyExcelUtils {

    public static void excel2Data(HSSFWorkbook wb, List<?> list) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Field[] fields = list.get(0).getClass().getDeclaredFields();
        String[] arr = new String[fields.length];
        for (Field f : fields) {
            MyExcel annotation = f.getAnnotation(MyExcel.class);
            arr[annotation.index()] = annotation.value();
        }

        HSSFCellStyle titleStyle = wb.createCellStyle();
        Font font = wb.createFont();
        // 设置单元格样式
        setSheetStyle(titleStyle, font);
        // 创建单元格 数据填充
        HSSFSheet sheet=wb.createSheet();
        HSSFRow row = sheet.createRow(0);
        // 表头做数据填充
        for (int i = 0; i < arr.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(arr[i]);
            cell.setCellStyle(titleStyle);
            sheet.autoSizeColumn(i,true);
        }
        // 数据行
        ExecutorService executor = Executors.newFixedThreadPool(10); // 创建一个固定大小为10的线程池




        for (int i = 0; i < list.size(); i++) {

            HSSFRow rows = sheet.createRow(i + 1);
            Object o = list.get(i);
            executor.execute(new DataProcessingTask(rows, o, fields, sheet)); // 提交任务给线程池执行
        }
        executor.shutdown(); // 关闭线程池
        wb.setSheetName(0, "数据表");
    }
    public static void setSheetStyle(HSSFCellStyle style, Font font) {
        //单元格背景色
        style.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        //单元格填充效果
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setAlignment(HorizontalAlignment.CENTER);    //左右居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);    //上下居中
        style.setBorderBottom(BorderStyle.MEDIUM);
        style.setBorderLeft(BorderStyle.MEDIUM);
        style.setBorderRight(BorderStyle.MEDIUM);
        style.setBorderTop(BorderStyle.MEDIUM);
        font.setFontHeightInPoints((short) 13);
        font.setFontName("仿宋_GB2312");
        style.setFont(font);//增加字体样式
    }



}
